import axios from 'axios'
import {
  Message,
  MessageBox,
  Loading
} from 'element-ui'
import store from '../store'
import {
  getToken
} from '@/utils/auth'

const precessEnv = process.env;
let curBaseUrl = '';
let loading = null;
// console.log('当前环境', precessEnv);
switch (precessEnv.NODE_ENV) {
  case 'production':
    // 生产环境地址
    curBaseUrl = 'https://cba360.com/kcbapi';
    // curBaseUrl = 'https://cba360.cn/kcbapi';
    break
  case 'development':
    // 开发环境地址
    curBaseUrl = 'https://cba360.com/kcbapi';
    // curBaseUrl = '/kcbapi';
    // curBaseUrl = 'http://101.132.173.193:8888/kcbapi';
    break
  default:
    curBaseUrl = '';
}

// 创建axios实例
const service = axios.create({
  baseURL: curBaseUrl, // api 的 base_url
  baseImgUrl: curBaseUrl.replace('/kcbapi', ''),
  timeout: 5 * 60 * 1000 // 请求超时时间 5分钟
});

// request拦截器
service.interceptors.request.use(
  config => {
    // console.log('请求配置', config);
    // 加载遮罩
    if (config.headers.isLoading != false) {
      // loading = Loading.service();
      loading = Loading.service({
        lock: true,
        text: '♪（＾∀＾●）加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      });
    }
    if (store.getters.token) {
      // 让每个请求携带自定义token 请根据实际情况自行修改
      config.headers['X-Token'] = getToken()
    }
    return config;
  },
  error => {
    console.log(error) // for debug
    Promise.reject(error);
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    // 关闭遮罩
    if (loading) setTimeout(() => {
      loading.close();
    }, 500);

    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    const res = response.data;
    if ((response && res.type == 'content-type:octet-stream') || response.config.responseType === 'blob') {
      // 返回的是文件
      return res;
    } else if (!response || !res || res.code == undefined) {
      let errorMsg = '无返回数据，请联系技术人员！<br />请求地址：<b>' + response.config.url + '</b>';
      if (!response || !res) errorMsg = '请求错误，请刷新后再试！';

      Message({
        message: errorMsg,
        dangerouslyUseHTMLString: true,
        type: 'error',
        duration: 5 * 1000
      });
      return Promise.reject(response);
    } else {
      if (res.code != 401 && res.code >= 0) {
        return response.data;
      } else {
        // 401:Token 过期了;
        if (res.code == 401) {
          MessageBox.confirm(
            `<b class="c-red">${res.msg??'您的登录已失效，需要重新登录！'}</b>`,
            '登录失效提示', {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning',
              closeOnClickModal: false,
              showCancelButton: false,
              showClose: false,
              dangerouslyUseHTMLString: true,
            }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload(); // 为了重新实例化vue-router对象 避免bug
            });
          });
        } else if (res.code < 0) { // code < 0
          // 此处注释掉，防止请求状态为0时，提示
          Message({
            message: res.msg,
            type: 'error',
            duration: 5 * 1000
          });
        }

        return res; //Promise.reject('error'); // 此处返回状态不为1也应该将传递数据
      }
    }
  },
  error => {
    // 关闭遮罩
    // if(loading) setTimeout(() => { loading.close(); }, 500);
    if (loading) loading.close();

    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
)

export default service;
